var app = getApp();
var c = require("../libs/common.js");
var cf = require('../libs/config.js');
var upimg = require('../libs/upimg.js');
var tim = app.globalData.tim;
var TIM = app.globalData.TIM;
Page({

  /**
   * 页面的初始数据
   */
  data: {
      test:[1,2,3]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showLoading({
      title: '列表加载中...',
      mask:true,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  
  getdoctorlist(){
    var that = this;
    var uid=wx.getStorageSync('userinfo').id;
    //登录腾讯IM
    c.ajax(
      cf.hostapi + 'Im/getLoginInfo', {
        uid: uid
      },
      res => {
        var loginInfo = res.data.data;
        //1v1单聊的话，一般只需要 'onConnNotify' 和 'onMsgNotify'就行了。
        //监听连接状态回调变化事件
        var onConnNotify = function (resp) {
          var info;
          switch (resp.ErrorCode) { //链接状态码
            case im.CONNECTION_STATUS.ON:
              im.Log.warn('建立连接成功: ' + resp.ErrorInfo);
              console.log('建立连接成功ww: ' + resp.ErrorInfo);
              console.log('aaavvv');
              var initUnreadMsgCount = im.syncMsgs(initUnreadMsgCount);
              console.log(initUnreadMsgCount);
              that.initRecentContactList();
              break;
            case im.CONNECTION_STATUS.OFF:
              info = '连接已断开，无法收到新消息，请检查下您的网络是否正常: ' + resp.ErrorInfo;
              im.Log.warn(info);
              console.log(info);
              break;
            case im.CONNECTION_STATUS.RECONNECT:
              info = '连接状态恢复正常: ' + resp.ErrorInfo;
              console.log(info);
              im.Log.warn(info);
              break;
            default:
              im.Log.error('未知连接状态: =' + resp.ErrorInfo); //错误信息
              console.log(info);
              break;
          }
        };

        //监听新消息事件     注：其中参数 newMsgList 为 webim.Msg 数组，即 [webim.Msg]。
        // newMsgList 为新消息数组，结构为[Msg]
        var onMsgNotify = function (newMsgList) {
          console.log('sessMapsessMapsessMap');
          console.log(newMsgList);
          var newsn = that.data.newsn;
          var selToID = '1';
          var sess, newMsg;
          //获取所有聊天会话
          // var sessMap = im.MsgStore.sessMap();
          var newsns = [];
          var type = newMsgList[0]['elems'][0]['type'];
          if (type == 'TIMImageElem') {
            var img = newMsgList[0]['elems'][0]['content']['ImageInfoArray'][2]['url'];
            var text = '';
          } else if (type == 'TIMTextElem') {
            var text = newMsgList[0]['elems'][0]['content']['text'];
            var img = '';
          }
          newsns = {
            'fromAccount': uid,
            'fromAccountNick': uid,
            'type': type,
            'text': text,
            'img': img ? img : ''
          }
          if (typeof (newsn)!='undefined'){
            var length = newsn.length;
            newsn[length] = newsns;
            console.log(newsn);
            that.setData({
              newsn: newsn
            });
            that.pageScrollToBottom();  
          }
          // return;
          // for (var j in newMsgList) { //遍历新消息
          //   newMsg = newMsgList[j];
          //   if (newMsg.getSession().id() == selToID) { //为当前聊天对象的消息
          //     var selSess = newMsg.getSession();
          //     console.log('aaaabbbbccccddddffff');
          //     console.log(newMsg);
          //     //在聊天窗体中新增一条消息
          //     //console.warn(newMsg);
          //     that.addMsg(newMsg);
          //   }
          // }
          // 消息已读上报，以及设置会话自动已读标记
          // im.setAutoRead(selSess, true, true);
          // for (var i in sessMap) {
          //   sess = sessMap[i];
          //   if (selToID != sess.id()) { //更新其他聊天对象的未读消息数
          //     updateSessDiv(sess.type(), sess.id(), sess.unread());
          //   }
          // }
        }


        var listener = {
          "onConnNotify": onConnNotify, //监听连接状态回调变化事件,必填
          // , "jsonpCallback": jsonpCallback//IE9(含)以下浏览器用到的 jsonp 回调函数，
          // ,
          "onMsgNotify": onMsgNotify, //监听新消息(私聊，普通群(非直播聊天室)消息，全员推送消息)事件，必填
          // , "onBigGroupMsgNotify": onBigGroupMsgNotify//监听新消息(直播聊天室)事件，直播场景下必填
          // , "onGroupSystemNotifys": onGroupSystemNotifys//监听（多终端同步）群系统消息事件，如果不需要监听，可不填
          // , "onGroupInfoChangeNotify": onGroupInfoChangeNotify//监听群资料变化事件，选填
          // , "onFriendSystemNotifys": onFriendSystemNotifys//监听好友系统通知事件，选填
          // , "onProfileSystemNotifys": onProfileSystemNotifys//监听资料系统（自己或好友）通知事件，选填
          // , "onKickedEventCall": onKickedEventCall//被其他登录实例踢下线
          // , "onC2cEventNotifys": onC2cEventNotifys//监听 C2C 系统消息通道
        };
        var data = {
          'MaxCnt': 10
        }
        imhandler.sdkLogin(loginInfo, listener);
        return;
      }
    ) 
  },

  clicklist(e){
    var conversationid = e.currentTarget.dataset.conversationid;
    wx.navigateTo({
      url: "../talkdetile/talkdetile?conversationid=" + conversationid,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  syncMsgs() {
   var info= im.syncMsgs();
   console.log(info);
  },
  getAllFriend() {
    var data = {
      'GetCount': 20
    }
    console.log(111222);
    im.getAllFriend(data, function(res) {}, function(res) {
      console.log(res)
    });
  },
  //处理消息（私聊(包括普通消息和全员推送消息)，普通群(非直播聊天室)消息） 我这里是只要私聊的
  addMsg: function(msg) {
    var that = this;
    var fromAccount, fromAccountNick, sessType, subType;
    fromAccount = msg.getFromAccount();
    if (!fromAccount) {
      fromAccount = '';
    }
    fromAccountNick = msg.getFromAccountNick();
    if (!fromAccountNick) {
      fromAccountNick = fromAccount;
    }
    //解析消息
    //获取会话类型
    //webim.SESSION_TYPE.GROUP-群聊，
    //webim.SESSION_TYPE.C2C-私聊，
    sessType = msg.getSession().type();
    //获取消息子类型
    //会话类型为群聊时，子类型为：webim.GROUP_MSG_SUB_TYPE
    //会话类型为私聊时，子类型为：webim.C2C_MSG_SUB_TYPE
    subType = msg.getSubType();
    switch (sessType) {
      case im.SESSION_TYPE.C2C: //私聊消息
        switch (subType) {
          case im.C2C_MSG_SUB_TYPE.COMMON: //c2c普通消息
            //业务可以根据发送者帐号fromAccount是否为app管理员帐号，来判断c2c消息是否为全员推送消息，还是普通好友消息
            //或者业务在发送全员推送消息时，发送自定义类型(webim.MSG_ELEMENT_TYPE.CUSTOM,即TIMCustomElem)的消息，在里面增加一个字段来标识消息是否为推送消息
            that.convertMsg(msg); //解析方法
            break;
        }
        break;
    }
  },

  convertMsg: function(msg) {
    var that = this;
    var elems, elem, type, content, isSelfSend;
    var loginInfo = that.data.loginInfo; //自己的资料
    var doctorInfo = that.data.doctorInfo; //对方的资料，这里要特别注意一下，消息里面是不会返回双方的头像和昵称的，只能通过指定的方法得到。
    elems = msg.getElems();
    isSelfSend = msg.getIsSend(); //消息是否为自己发的 true是自己发送，
    var sess = msg.sess;
    var currentMsg = {}; //设置消息数组，存消息
    var currentMsgsArray = that.data.currentMsgsArray;
    var allChatList = that.data.allChatList;
    for (var i in elems) {
      elem = elems[i];
      type = elem.getType();
      content = elem.getContent();
      switch (type) {
        case im.MSG_ELEMENT_TYPE.TEXT:
          // var msgContent = that.convertTextMsg(content);
          var msgContent = content;
          var msgTime = msg.getTime(); //得到当前消息发送的时间
          //得到当天凌晨的时间戳
          var timeStamp = new Date(new Date().setHours(0, 0, 0, 0)) / 1000;
          var thisdate;
          var d = new Date(msgTime * 1000); //根据时间戳生成的时间对象
          var min = d.getMinutes();
          var hour = d.getHours();
          //得到时和分，分小于10时，只返回一位数
          if (min < 10) {
            min = "0" + min;
          }
          //得到月份和天  月份一般是从0开始，所以展示出来要+1
          var month = d.getMonth();

          var day = d.getDate();
          //得到时间   当天时间应该只显示时分  当天以前显示日期+时间
          if (timeStamp > msgTime) {
            thisdate = ((month + 1) + '-' + day + ' ' + hour + ":" + min);
          } else {
            thisdate = (hour + ":" + min);
          }
          currentMsg.msgContent = msgContent; //当前消息的内容
          currentMsg.msgTime = thisdate;
          currentMsg.isSelfSend = isSelfSend;
          //根据是否自己发送的消息，设置双方的头像
          if (isSelfSend) {
            currentMsg.avatarUrl = loginInfo.head;
          } else {
            currentMsg.avatarUrl = doctorInfo.head;
          }
          console.log('bbbbbbbbbbbbbbbbbbbbccccccccccccc');
          console.log(currentMsg);
          console.log(typeof(currentMsg));
          return;
          //然后将每一条聊天消息push进数组
          currentMsgsArray.push(currentMsg);
          that.setData({
            currentMsgsArray: currentMsgsArray,
          })
          console.log('currentMsgsArraycurrentMsgsArraycurrentMsgsArray');
          console.log(currentMsgsArray);
          break;
      }

    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

    var that=this;
    that.getMeList();
    let onMessageReceived = function (event) {
      that.getMeList();
    };
    tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
  },
   
   getMeList:function(){
     // 监听事件，如：
     var that = this;
     // 收到离线消息和会话列表同步完毕通知，接入侧可以调用 sendMessage 等需要鉴权的接口
     // event.name - TIM.EVENT.SDK_READY
     // 拉取会话列表
     let promiselist = tim.getConversationList();
     promiselist.then(function (imResponse) {
       const conversationList = imResponse.data.conversationList; // 会话列表，用该列表覆盖原有的会话列表
       console.log('会话列表');
       console.log(conversationList);
       wx.hideLoading();
       that.setData({ contactList: conversationList })
     }).catch(function (imError) {
       console.warn('getConversationList error:', imError); // 获取会话列表失败的相关信息
     });
   },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  getC2CHistoryMsgs() {
    var uid=wx.getStorageSync('userinfo').id;
    var that = this;
    var newsn = [];
    var options = {
      'Peer_Account': uid, //指定的好友帐号
      'MaxCnt': 10, //拉取的消息数目
      'LastMsgTime': 0, //上一次拉取的时间  在第一次拉去消息的时候，这里必须为0
      'MsgKey': ''
    }

    im.getC2CHistoryMsgs(options, function(res) {
      var sMsgListsinfo = res.MsgList;
      var newsn = [];
      var fromAccount = '';
      var fromAccountNick = '';
      var type = '';
      var text = '';
      var img = [];
      for (var i = 0; i < sMsgListsinfo.length; i++) {
        fromAccount = sMsgListsinfo[i]['fromAccount'];
        fromAccountNick = sMsgListsinfo[i]['fromAccountNick'];
        type = sMsgListsinfo[i]['elems'][0]['type'];
        text = sMsgListsinfo[i]['elems'][0]['content']['text'];
        img = (type == 'TIMImageElem') ? sMsgListsinfo[i]['elems'][0]['content']['ImageInfoArray'][2]['url'] : 'no';
        newsn[i] = {
          'fromAccount': fromAccount,
          'fromAccountNick': fromAccountNick,
          'type': type,
          'text': text,
          'img': img
        }
      };
      that.setData({
        newsn: newsn
      })

    });

  },
  getRecentContactList() {
    var options = {
      'Count': 10,
    }
    im.getRecentContactList(options, function(res) {
      console.log(res)
    })
  },

  //初始化聊天界面最近会话列表
  initRecentContactList: function() {
    var that = this;
    im.getRecentContactList({ //获取会话列表的方法
      'Count': 10 //最近的会话数 ,最大为 100
    }, function(resp) {
      if(typeof (resp.SessionItem) !='undefined'){
        wx.showLoading({
          title: '加载中...',
        })
        for (var i = 0; i < resp.SessionItem.length; i++) {
          console.log(resp.SessionItem[i]);
          resp.SessionItem[i]['MsgTimeStampSet'] = c.getDateDiff(resp.SessionItem[i]['MsgTimeStamp'] * 1000);
        }
        console.log(resp);
        if (resp.SessionItem) {

          if (resp.SessionItem.length == 0) {
            that.setData({
              isNoData: false,
            })
            wx.hideLoading()
          } else if (resp.SessionItem.length > 0) {
            console.log('resresresresresresres');
            console.log(resp.SessionItem);
            that.setData({
              contactList: resp.SessionItem,
              isNoData: true
            })
            wx.hideLoading();
          }
        }
      }else{
        that.setData({
          contactList: ''
        })
        wx.hideLoading();
      };

    }, 
    function(resp) {
      //错误回调
    });
  },


  
  //获取会话列表所有用户头像
  getAvatar: function(userId, item, callback) {
    if (!callback) {
      callback = () => {

      }
    }
    var that = this;
    var tag_list = ['Tag_Profile_IM_Nick', 'Tag_Profile_IM_Image']
    //用户id
    var account = userId
    var options = {
      From_Account: '1',
      To_Account: ['doctor10'],
      LastStandardSequence: 0,
      TagList: tag_list,
    };
    var contactList = [];

    im.getProfilePortrait(
      options,
      function(res) {
        var UserProfileItem = res.UserProfileItem;
        var C2cNick, C2cImage;
        for (var i = 0; i < UserProfileItem.length; i++) {
          var data = UserProfileItem[i].ProfileItem;
          console.log(res);
          // 循环添加昵称和头像
          // contactList = item.map((item, index) => {
          //   item.C2cNick = UserProfileItem[index].ProfileItem[0].Value

          //   item.C2cImage = UserProfileItem[index].ProfileItem[1].Value
          //   return item;
          // })
        }
        contactList = contactList.map((item, index) => {
          var MsgTimeStamp = util.getDateDiff(item.MsgTimeStamp * 1000)
          item.MsgTimeStamp = MsgTimeStamp;
          return item;
        })
        callback(contactList)
      },
      function(res) {
        console.log(res);
      }
    )

  },

  unread: function() {
    //获取全局的sessMap
    var sessMap = im.MsgStore.sessMap();
    //这里的GROUPID为"GROUP"+群id
    //C2CID为"C2C"+identifier
    console.log(sessMap["C2C5"]);
  },

  sendMsg: function() {
    var that = this;
    var msg = 'halou';
    var img = '';
    var info = imhandler.onSendMsg(msg);
    var newsn = that.data.newsn;
    var newsns = [];
    newsns = {
      'fromAccount': '1',
      'fromAccountNick': '小王',
      'type': 'TIMTextElem',
      'text': msg,
      'img': img ? img : ''
    };
    var length = newsn.length;
    newsn[length] = newsns;
    that.setData({
      newsn: newsn
    });
  },

  //发送图片
  sendPic: function() {
      var path = 'talk/' + new Date().getTime() + '.png';
      var that = this;
      var i;
      var returninfo = upimg.simpleUpload(
        path,
        function (res) {
          for (i = 0; i < res.length;i++){
            that.sendPicApi(res[i]['imgLocation']);
          }
        },
        6
      );
  },


  sendPicApi(url,touid) {
    console.log('url----'+url);
    var selToID = '5';
    var selSess = '';
    var images = {
      "ActionStatus": "OK",
      "From_Account": "5",
      "To_Account": "1",
      "App_Version": "2.1",
      "Appid": 1400133121,
      "Seq": 9971632,
      "Random": 4091267451,
      "Timestamp": 1548298613,
      "ErrorCode": 0,
      "IsRejectRetry": 0,
      "ErrorInfo": "",
      "Next_Offset": 0,
      "IsFinish": 1,
      "File_UUID": "15614_8046C9C6C5A318C4206A4AC661297FAD",
      "URL_INFO": [{
        "PIC_TYPE": 2,
        "DownUrl": url,
        "PIC_Width": 198,
        "PIC_Height": 198,
        "PIC_Size": 0
      }]
    };

    if (!selSess) {
      selSess = new im.Session('C2C', selToID, selToID, 'img/friend.jpg',
        Math.round(new Date().getTime() / 1000));
    }
    var msg = new im.Msg(selSess, true);
    var images_obj = new im.Msg.Elem.Images(images.File_UUID);
    for (var i in images.URL_INFO) {
      var img = images.URL_INFO[i];
      var newImg;
      var type;
      switch (img.PIC_TYPE) {
        case 1: //原图
          type = 1; //原图
          break;
        case 2: //小图（缩略图）
          type = 3; //小图
          break;
        case 4: //大图
          type = 2; //大图
          break;
      }
      newImg = new im.Msg.Elem.Images.Image(type, img.PIC_Size, img.PIC_Width,
        img.PIC_Height, img.DownUrl);
      images_obj.addImage(newImg);
    }
    msg.addImage(images_obj);
    //调用发送图片接口
    im.sendMsg(msg, function(resp) {

      // curMsgCount++;
    }, function(err) {
      alert(err.ErrorInfo);
    });
  },

  clickdoc:function(){
    wx.navigateTo({
      url: '/pages/doctorList/doctorList',
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  }
})